package cn.iocoder.yudao.module.ao.service.teacher;

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.HashMap;
import java.util.Map;
import cn.iocoder.yudao.module.ao.controller.admin.teacher.vo.*;
import cn.iocoder.yudao.module.ao.dal.dataobject.teacher.TeacherDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.ao.dal.mysql.teacher.TeacherMapper;
import cn.iocoder.yudao.module.ao.dal.mysql.vocationalclassschedule.VocationalClassScheduleMapper;
import cn.iocoder.yudao.module.ao.dal.dataobject.vocationalclassschedule.VocationalClassScheduleDO;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.hutool.core.util.StrUtil;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.yudao.module.ao.enums.ErrorCodeConstants.*;

/**
 * 教师信息 Service 实现类
 *
 * @author 智教云枢
 */
@Service
@Validated
@Slf4j
public class TeacherServiceImpl implements TeacherService {

    @Resource
    private TeacherMapper teacherMapper;

    @Resource
    private VocationalClassScheduleMapper vocationalClassScheduleMapper;

    @Override
    public Long createTeacher(TeacherSaveReqVO createReqVO) {
        // 插入
        TeacherDO teacher = BeanUtils.toBean(createReqVO, TeacherDO.class);
        teacherMapper.insert(teacher);

        // 返回
        return teacher.getTeacherId();
    }

    @Override
    public void updateTeacher(TeacherSaveReqVO updateReqVO) {
        // 校验存在
        validateTeacherExists(updateReqVO.getTeacherId());
        // 更新
        TeacherDO updateObj = BeanUtils.toBean(updateReqVO, TeacherDO.class);
        teacherMapper.updateById(updateObj);
    }

    @Override
    public void deleteTeacher(Long id) {
        // 校验存在
        validateTeacherExists(id);
        // 删除
        teacherMapper.deleteById(id);
    }

    @Override
        public void deleteTeacherListByIds(List<Long> ids) {
        // 删除
        teacherMapper.deleteByIds(ids);
        }


    private void validateTeacherExists(Long id) {
        if (teacherMapper.selectById(id) == null) {
            throw exception(TEACHER_NOT_EXISTS);
        }
    }

    @Override
    public TeacherDO getTeacher(Long id) {
        return teacherMapper.selectById(id);
    }

    @Override
    public PageResult<TeacherDO> getTeacherPage(TeacherPageReqVO pageReqVO) {
        return teacherMapper.selectPage(pageReqVO);
    }

    @Override
    public List<String> getTeacherCourses(Long teacherId) {
        TeacherDO teacher = getTeacher(teacherId);
        if (teacher == null) {
            return new ArrayList<>();
        }
        return getTeacherCoursesByName(teacher.getTeacherName());
    }

    @Override
    public List<String> getTeacherCoursesByName(String teacherName) {
        if (StrUtil.isBlank(teacherName)) {
            return new ArrayList<>();
        }

        List<VocationalClassScheduleDO> allSchedules = vocationalClassScheduleMapper.selectList(new LambdaQueryWrapperX<>());
        Set<String> teacherCourses = new HashSet<>();

        for (VocationalClassScheduleDO schedule : allSchedules) {
            extractCoursesFromScheduleField(schedule.getMondayCourse(), teacherName, teacherCourses);
            extractCoursesFromScheduleField(schedule.getTuesdayCourse(), teacherName, teacherCourses);
            extractCoursesFromScheduleField(schedule.getWednesdayCourse(), teacherName, teacherCourses);
            extractCoursesFromScheduleField(schedule.getThursdayCourse(), teacherName, teacherCourses);
            extractCoursesFromScheduleField(schedule.getFridayCourse(), teacherName, teacherCourses);
            extractCoursesFromScheduleField(schedule.getSaturdayCourse(), teacherName, teacherCourses);
            extractCoursesFromScheduleField(schedule.getSundayCourse(), teacherName, teacherCourses);
        }

        return new ArrayList<>(teacherCourses);
    }

    @Override
    public Map<String, Object> getTeacherSchedule(Long teacherId) {
        TeacherDO teacher = getTeacher(teacherId);
        if (teacher == null) {
            return new HashMap<>();
        }

        List<VocationalClassScheduleDO> allSchedules = vocationalClassScheduleMapper.selectList(new LambdaQueryWrapperX<>());

        Map<String, Object> result = new HashMap<>();
        result.put("teacherName", teacher.getTeacherName());
        result.put("major", teacher.getMajor()); // 使用专业字段替代科目字段
        result.put("position", teacher.getPosition()); // 添加职务信息

        // 构建课程表数据结构
        List<Map<String, Object>> scheduleGrid = new ArrayList<>();
        Map<String, Map<String, String>> sectionMap = new HashMap<>();

        for (VocationalClassScheduleDO schedule : allSchedules) {
            String section = schedule.getClassSection();
            if (StrUtil.isBlank(section)) {
                continue;
            }

            Map<String, String> weekCourses = sectionMap.computeIfAbsent(section, k -> new HashMap<>());

            checkAndAddCourse(schedule.getMondayCourse(), teacher.getTeacherName(), "monday", weekCourses, schedule);
            checkAndAddCourse(schedule.getTuesdayCourse(), teacher.getTeacherName(), "tuesday", weekCourses, schedule);
            checkAndAddCourse(schedule.getWednesdayCourse(), teacher.getTeacherName(), "wednesday", weekCourses, schedule);
            checkAndAddCourse(schedule.getThursdayCourse(), teacher.getTeacherName(), "thursday", weekCourses, schedule);
            checkAndAddCourse(schedule.getFridayCourse(), teacher.getTeacherName(), "friday", weekCourses, schedule);
            checkAndAddCourse(schedule.getSaturdayCourse(), teacher.getTeacherName(), "saturday", weekCourses, schedule);
            checkAndAddCourse(schedule.getSundayCourse(), teacher.getTeacherName(), "sunday", weekCourses, schedule);
        }

        // 转换为前端需要的格式，并按时间排序
        List<String> sortedSections = sectionMap.keySet().stream()
            .filter(section -> !sectionMap.get(section).isEmpty())
            .sorted(this::compareSections)
            .collect(java.util.stream.Collectors.toList());

        for (String section : sortedSections) {
            Map<String, String> weekCourses = sectionMap.get(section);
            Map<String, Object> row = new HashMap<>();
            row.put("section", section);
            row.put("monday", weekCourses.get("monday"));
            row.put("tuesday", weekCourses.get("tuesday"));
            row.put("wednesday", weekCourses.get("wednesday"));
            row.put("thursday", weekCourses.get("thursday"));
            row.put("friday", weekCourses.get("friday"));
            row.put("saturday", weekCourses.get("saturday"));
            row.put("sunday", weekCourses.get("sunday"));
            scheduleGrid.add(row);
        }

        result.put("scheduleGrid", scheduleGrid);
        return result;
    }

    /**
     * 比较节次时间，用于排序
     */
    private int compareSections(String section1, String section2) {
        String time1 = extractTimeFromSection(section1);
        String time2 = extractTimeFromSection(section2);

        if (time1 == null && time2 == null) {
            return section1.compareTo(section2);
        }
        if (time1 == null) return 1;
        if (time2 == null) return -1;

        return time1.compareTo(time2);
    }

    /**
     * 从节次字符串中提取时间
     */
    private String extractTimeFromSection(String section) {
        if (StrUtil.isBlank(section)) {
            return null;
        }

        // 匹配时间格式，如 "08:00-08:45" 或 "8:00-8:45"
        Pattern timePattern = Pattern.compile("(\\d{1,2}:\\d{2})");
        Matcher matcher = timePattern.matcher(section);

        if (matcher.find()) {
            String time = matcher.group(1);
            // 标准化时间格式，确保是两位数的小时
            if (time.length() == 4) { // 如 "8:00"
                time = "0" + time;
            }
            return time;
        }

        return null;
    }

    private void extractCoursesFromScheduleField(String courseField, String teacherName, Set<String> teacherCourses) {
        if (StrUtil.isBlank(courseField) || StrUtil.isBlank(teacherName)) {
            return;
        }

        String[] parts = courseField.trim().split("\\s+");
        if (parts.length >= 2) {
            String courseTeacher = parts[1].trim();
            String cleanedTeacher = cleanTeacherName(courseTeacher);
            String cleanedTargetTeacher = cleanTeacherName(teacherName);

            if (StrUtil.equals(cleanedTeacher, cleanedTargetTeacher)) {
                String courseName = parts[0].trim();
                if (StrUtil.isNotBlank(courseName)) {
                    teacherCourses.add(courseName);
                }
            }
        }
    }

    private void checkAndAddCourse(String courseField, String teacherName, String dayOfWeek,
                                   Map<String, String> weekCourses, VocationalClassScheduleDO schedule) {
        if (StrUtil.isBlank(courseField) || StrUtil.isBlank(teacherName)) {
            return;
        }

        String[] parts = courseField.trim().split("\\s+");
        if (parts.length >= 2) {
            String courseTeacher = parts[1].trim();
            String cleanedTeacher = cleanTeacherName(courseTeacher);
            String cleanedTargetTeacher = cleanTeacherName(teacherName);

            if (StrUtil.equals(cleanedTeacher, cleanedTargetTeacher)) {
                String courseName = parts[0].trim();
                String classroom = parts.length >= 3 ? parts[2].trim() : "";
                String className = schedule.getClassName();

                StringBuilder courseInfo = new StringBuilder(courseName);
                if (StrUtil.isNotBlank(className)) {
                    courseInfo.append("\n").append(className);
                }
                if (StrUtil.isNotBlank(classroom)) {
                    courseInfo.append("\n").append(classroom);
                }

                weekCourses.put(dayOfWeek, courseInfo.toString());
            }
        }
    }

    private String cleanTeacherName(String teacherName) {
        if (StrUtil.isBlank(teacherName)) {
            return "";
        }

        String cleaned = teacherName.trim();
        if (cleaned.endsWith("老师")) {
            cleaned = cleaned.substring(0, cleaned.length() - 2);
        } else if (cleaned.endsWith("教师")) {
            cleaned = cleaned.substring(0, cleaned.length() - 2);
        } else if (cleaned.endsWith("讲师")) {
            cleaned = cleaned.substring(0, cleaned.length() - 2);
        } else if (cleaned.endsWith("教授")) {
            cleaned = cleaned.substring(0, cleaned.length() - 2);
        }

        return cleaned.trim();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TeacherImportRespVO importTeacherList(List<TeacherImportExcelVO> importTeachers, boolean isUpdateSupport) {
        if (CollUtil.isEmpty(importTeachers)) {
            throw exception(TEACHER_IMPORT_LIST_IS_EMPTY);
        }

        log.info("开始导入教师数据，总数量：{}，是否支持更新：{}", importTeachers.size(), isUpdateSupport);

        // 简化的导入信息
        if (!importTeachers.isEmpty()) {
            TeacherImportExcelVO firstTeacher = importTeachers.get(0);
            log.info("导入数据示例 - 姓名：{}，部门：{}，工号：{}",
                    firstTeacher.getTeacherName(),
                    firstTeacher.getDeptName(),
                    firstTeacher.getTeacherNo());
        }

        TeacherImportRespVO respVO = TeacherImportRespVO.builder()
                .createTeacherCount(0).updateTeacherCount(0).failureTeacherCount(0)
                .failureTeacherNames(new ArrayList<>()).build();

        importTeachers.forEach(importTeacher -> {
            try {
                log.info("处理教师：{}", importTeacher.getTeacherName());

                // 校验教师姓名不能为空
                if (StrUtil.isBlank(importTeacher.getTeacherName())) {
                    log.warn("教师姓名为空，跳过处理");
                    respVO.setFailureTeacherCount(respVO.getFailureTeacherCount() + 1);
                    respVO.getFailureTeacherNames().add("教师姓名为空");
                    return;
                }

                // 根据教师姓名查询是否存在
                TeacherDO existTeacher = getTeacherByName(importTeacher.getTeacherName());
                if (existTeacher != null) {
                    log.info("教师 {} 已存在，ID：{}，是否支持更新：{}", importTeacher.getTeacherName(), existTeacher.getTeacherId(), isUpdateSupport);
                    // 教师已存在
                    if (!isUpdateSupport) {
                        respVO.setFailureTeacherCount(respVO.getFailureTeacherCount() + 1);
                        respVO.getFailureTeacherNames().add(importTeacher.getTeacherName() + "：教师已存在");
                        return;
                    }
                    // 更新教师信息
                    updateTeacherFromImport(existTeacher, importTeacher);
                    respVO.setUpdateTeacherCount(respVO.getUpdateTeacherCount() + 1);
                    log.info("成功更新教师：{}", importTeacher.getTeacherName());
                } else {
                    log.info("教师 {} 不存在，创建新记录", importTeacher.getTeacherName());
                    // 新增教师
                    createTeacherFromImport(importTeacher);
                    respVO.setCreateTeacherCount(respVO.getCreateTeacherCount() + 1);
                    log.info("成功创建教师：{}", importTeacher.getTeacherName());
                }
            } catch (Exception ex) {
                log.error("处理教师 {} 时发生异常：{}", importTeacher.getTeacherName(), ex.getMessage(), ex);
                respVO.setFailureTeacherCount(respVO.getFailureTeacherCount() + 1);
                respVO.getFailureTeacherNames().add(importTeacher.getTeacherName() + "：" + ex.getMessage());
            }
        });

        log.info("导入完成，创建：{}，更新：{}，失败：{}", respVO.getCreateTeacherCount(), respVO.getUpdateTeacherCount(), respVO.getFailureTeacherCount());
        return respVO;
    }

    @Override
    public TeacherDO getTeacherByName(String teacherName) {
        return teacherMapper.selectOne(new LambdaQueryWrapperX<TeacherDO>()
                .eq(TeacherDO::getTeacherName, teacherName));
    }

    /**
     * 从导入数据创建教师
     */
    private void createTeacherFromImport(TeacherImportExcelVO importTeacher) {
        TeacherDO teacher = convertImportToTeacher(importTeacher);
        teacherMapper.insert(teacher);
    }

    /**
     * 从导入数据更新教师信息
     */
    private void updateTeacherFromImport(TeacherDO existTeacher, TeacherImportExcelVO importTeacher) {
        log.info("开始更新教师信息，教师ID：{}，姓名：{}", existTeacher.getTeacherId(), existTeacher.getTeacherName());

        // 记录更新前的信息
        String oldInfo = String.format("更新前 - 工号：%s，职务：%s，性别：%s，年龄：%s",
            existTeacher.getTeacherNo(), existTeacher.getPosition(), existTeacher.getGender(), existTeacher.getAge());
        log.info(oldInfo);

        // 只更新非空字段
        int updateCount = 0;
        if (StrUtil.isNotBlank(importTeacher.getTeacherNo())) {
            existTeacher.setTeacherNo(importTeacher.getTeacherNo());
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getPosition())) {
            existTeacher.setPosition(importTeacher.getPosition());
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getGenderStr())) {
            existTeacher.setGender(convertGender(importTeacher.getGenderStr()));
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getAgeStr())) {
            existTeacher.setAge(convertAge(importTeacher.getAgeStr()));
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getMaritalStatusStr())) {
            existTeacher.setMaritalStatus(convertMaritalStatus(importTeacher.getMaritalStatusStr()));
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getEthnicity())) {
            existTeacher.setEthnicity(importTeacher.getEthnicity());
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getIdCard())) {
            existTeacher.setIdCard(importTeacher.getIdCard());
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getContactPhone())) {
            existTeacher.setContactPhone(importTeacher.getContactPhone());
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getEntryYearStr())) {
            existTeacher.setEntryYear(convertEntryYear(importTeacher.getEntryYearStr()));
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getEntryMonthStr())) {
            existTeacher.setEntryMonth(convertEntryMonth(importTeacher.getEntryMonthStr()));
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getServiceYearsStr())) {
            existTeacher.setServiceYears(convertServiceYears(importTeacher.getServiceYearsStr()));
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getEducationLevel())) {
            existTeacher.setEducationLevel(importTeacher.getEducationLevel());
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getMajor())) {
            existTeacher.setMajor(importTeacher.getMajor());
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getGraduateSchool())) {
            existTeacher.setGraduateSchool(importTeacher.getGraduateSchool());
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getProfessionalTitle())) {
            existTeacher.setProfessionalTitle(importTeacher.getProfessionalTitle());
            updateCount++;
        }

        // 更新日期字段
        if (StrUtil.isNotBlank(importTeacher.getBirthDateStr())) {
            existTeacher.setBirthDate(convertDate(importTeacher.getBirthDateStr()));
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getEntryDateStr())) {
            existTeacher.setEntryDate(convertDate(importTeacher.getEntryDateStr()));
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getCertificateIssueDateStr())) {
            existTeacher.setCertificateIssueDate(convertDate(importTeacher.getCertificateIssueDateStr()));
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getContractSignDateStr())) {
            existTeacher.setContractSignDate(convertDate(importTeacher.getContractSignDateStr()));
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getContractExpireDateStr())) {
            existTeacher.setContractExpireDate(convertDate(importTeacher.getContractExpireDateStr()));
            updateCount++;
        }
        if (StrUtil.isNotBlank(importTeacher.getGraduationDateStr())) {
            existTeacher.setGraduationDate(convertDate(importTeacher.getGraduationDateStr()));
            updateCount++;
        }

        log.info("更新教师 {} 的 {} 个字段", existTeacher.getTeacherName(), updateCount);
        teacherMapper.updateById(existTeacher);
    }

    /**
     * 将导入数据转换为教师DO
     */
    private TeacherDO convertImportToTeacher(TeacherImportExcelVO importTeacher) {
        TeacherDO teacher = new TeacherDO();
        teacher.setTeacherName(importTeacher.getTeacherName());
        teacher.setTeacherNo(importTeacher.getTeacherNo());
        teacher.setPosition(importTeacher.getPosition());
        teacher.setGender(convertGender(importTeacher.getGenderStr()));
        teacher.setAge(convertAge(importTeacher.getAgeStr()));
        teacher.setMaritalStatus(convertMaritalStatus(importTeacher.getMaritalStatusStr()));
        teacher.setEthnicity(importTeacher.getEthnicity());
        teacher.setIdCard(importTeacher.getIdCard());
        teacher.setContactPhone(importTeacher.getContactPhone());
        teacher.setEntryYear(convertEntryYear(importTeacher.getEntryYearStr()));
        teacher.setEntryMonth(convertEntryMonth(importTeacher.getEntryMonthStr()));
        teacher.setServiceYears(convertServiceYears(importTeacher.getServiceYearsStr()));
        teacher.setHouseholdType(importTeacher.getHouseholdType());
        teacher.setNativePlace(importTeacher.getNativePlace());
        teacher.setHouseholdAddress(importTeacher.getHouseholdAddress());
        teacher.setCurrentAddress(importTeacher.getCurrentAddress());
        teacher.setEducationLevel(importTeacher.getEducationLevel());
        teacher.setMajor(importTeacher.getMajor());
        teacher.setGraduateSchool(importTeacher.getGraduateSchool());
        teacher.setProfessionalCertificate(importTeacher.getProfessionalCertificate());
        teacher.setTeachingCertificateNo(importTeacher.getTeachingCertificateNo());
        teacher.setCertificateIssuer(importTeacher.getCertificateIssuer());
        teacher.setContractCount(convertContractCount(importTeacher.getContractCountStr()));
        teacher.setSocialInsurance(importTeacher.getSocialInsurance());
        teacher.setEmergencyContact(importTeacher.getEmergencyContact());
        teacher.setPersonalEmail(importTeacher.getPersonalEmail());
        teacher.setQqNumber(importTeacher.getQqNumber());
        teacher.setPoliticalStatus(importTeacher.getPoliticalStatus());
        teacher.setPersonnelChanges(importTeacher.getPersonnelChanges());
        teacher.setHobbiesSpecialties(importTeacher.getHobbiesSpecialties());
        teacher.setProfessionalLevel(importTeacher.getProfessionalLevel());
        teacher.setProfessionalTitle(importTeacher.getProfessionalTitle());

        // 添加日期字段的转换逻辑
        teacher.setBirthDate(convertDate(importTeacher.getBirthDateStr()));
        teacher.setEntryDate(convertDate(importTeacher.getEntryDateStr()));
        teacher.setCertificateIssueDate(convertDate(importTeacher.getCertificateIssueDateStr()));
        teacher.setContractSignDate(convertDate(importTeacher.getContractSignDateStr()));
        teacher.setContractExpireDate(convertDate(importTeacher.getContractExpireDateStr()));
        teacher.setGraduationDate(convertDate(importTeacher.getGraduationDateStr()));

        return teacher;
    }

    /**
     * 转换年龄字符串为数字
     */
    private Integer convertAge(String ageStr) {
        if (StrUtil.isBlank(ageStr)) {
            return null;
        }
        try {
            // 移除可能的中文字符，只保留数字
            String numStr = ageStr.replaceAll("[^0-9]", "");
            return StrUtil.isBlank(numStr) ? null : Integer.parseInt(numStr);
        } catch (NumberFormatException e) {
            log.warn("年龄转换失败：{}", ageStr);
            return null;
        }
    }

    /**
     * 转换入职年份字符串为数字
     */
    private Integer convertEntryYear(String entryYearStr) {
        if (StrUtil.isBlank(entryYearStr)) {
            return null;
        }
        try {
            // 移除可能的中文字符，只保留数字
            String numStr = entryYearStr.replaceAll("[^0-9]", "");
            return StrUtil.isBlank(numStr) ? null : Integer.parseInt(numStr);
        } catch (NumberFormatException e) {
            log.warn("入职年份转换失败：{}", entryYearStr);
            return null;
        }
    }

    /**
     * 转换入职月份字符串为数字
     */
    private Integer convertEntryMonth(String entryMonthStr) {
        if (StrUtil.isBlank(entryMonthStr)) {
            return null;
        }
        try {
            // 移除可能的中文字符，只保留数字
            String numStr = entryMonthStr.replaceAll("[^0-9]", "");
            return StrUtil.isBlank(numStr) ? null : Integer.parseInt(numStr);
        } catch (NumberFormatException e) {
            log.warn("入职月份转换失败：{}", entryMonthStr);
            return null;
        }
    }

    /**
     * 转换签合同次数字符串为数字
     */
    private Integer convertContractCount(String contractCountStr) {
        if (StrUtil.isBlank(contractCountStr)) {
            return null;
        }
        try {
            // 移除可能的中文字符，只保留数字
            String numStr = contractCountStr.replaceAll("[^0-9]", "");
            return StrUtil.isBlank(numStr) ? null : Integer.parseInt(numStr);
        } catch (NumberFormatException e) {
            log.warn("签合同次数转换失败：{}", contractCountStr);
            return null;
        }
    }

    /**
     * 转换性别字符串为数字
     */
    private Integer convertGender(String genderStr) {
        if (StrUtil.isBlank(genderStr)) {
            return null;
        }
        if ("男".equals(genderStr.trim())) {
            return 1;
        } else if ("女".equals(genderStr.trim())) {
            return 2;
        }
        return null;
    }

    /**
     * 转换婚姻状态字符串为数字
     */
    private Integer convertMaritalStatus(String maritalStatusStr) {
        if (StrUtil.isBlank(maritalStatusStr)) {
            return null;
        }
        if ("已婚".equals(maritalStatusStr.trim()) || "是".equals(maritalStatusStr.trim())) {
            return 1;
        } else if ("未婚".equals(maritalStatusStr.trim()) || "否".equals(maritalStatusStr.trim())) {
            return 0;
        }
        return null;
    }

    /**
     * 转换工作年限字符串为BigDecimal
     */
    private BigDecimal convertServiceYears(String serviceYearsStr) {
        if (StrUtil.isBlank(serviceYearsStr)) {
            return null;
        }
        try {
            // 移除可能的中文字符，只保留数字和小数点
            String numStr = serviceYearsStr.replaceAll("[^0-9.]", "");
            return StrUtil.isBlank(numStr) ? null : new BigDecimal(numStr);
        } catch (NumberFormatException e) {
            log.warn("工作年限转换失败：{}", serviceYearsStr);
            return null;
        }
    }

    /**
     * 转换日期字符串为LocalDate对象
     */
    private LocalDate convertDate(String dateStr) {
        if (StrUtil.isBlank(dateStr)) {
            return null;
        }

        try {
            // 预处理日期字符串
            String cleanDateStr = preprocessDateString(dateStr.trim());

            // 如果预处理后为空或无效，返回null
            if (StrUtil.isBlank(cleanDateStr) || "无固定期限合同".equals(cleanDateStr)) {
                return null;
            }

            // 尝试多种日期格式
            String[] patterns = {
                "yyyy年MM月dd日",
                "yyyy-MM-dd",
                "yyyy/MM/dd",
                "yyyy年M月d日",
                "yyyy.MM.dd",
                "yyyy.M.d",
                "yyyy年MM月d日",
                "yyyy年M月dd日"
            };

            for (String pattern : patterns) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                    sdf.setLenient(false); // 严格模式
                    Date date = sdf.parse(cleanDateStr);
                    return date.toInstant()
                            .atZone(ZoneId.systemDefault())
                            .toLocalDate();
                } catch (ParseException ignored) {
                    // 继续尝试下一个格式
                }
            }

            log.warn("日期转换失败，无法识别格式：{}", dateStr);
            return null;
        } catch (Exception e) {
            log.warn("日期转换失败：{}", dateStr, e);
            return null;
        }
    }

    /**
     * 预处理日期字符串，处理特殊格式
     */
    private String preprocessDateString(String dateStr) {
        if (StrUtil.isBlank(dateStr)) {
            return null;
        }

        // 处理包含星期的中文日期格式：星期一, 十二月 24, 2012
        if (dateStr.contains("星期") && dateStr.contains("月") && dateStr.contains(",")) {
            return parseChineseDateWithWeekday(dateStr);
        }

        // 修复格式错误：2024年09年20日 -> 2024年09月20日
        if (dateStr.matches("\\d{4}年\\d{2}年\\d{2}日")) {
            dateStr = dateStr.replaceFirst("年(\\d{2})年", "年$1月");
            log.info("修复日期格式错误：{}", dateStr);
        }

        // 处理其他可能的格式问题
        dateStr = dateStr.replace("年年", "年").replace("月月", "月");

        return dateStr;
    }

    /**
     * 解析中文星期日期格式：星期一, 十二月 24, 2012
     */
    private String parseChineseDateWithWeekday(String dateStr) {
        try {
            // 移除星期部分和逗号
            String cleanStr = dateStr.replaceAll("星期[一二三四五六日天],?\\s*", "").trim();

            // 中文月份映射
            Map<String, String> monthMap = new HashMap<>();
            monthMap.put("一月", "01");
            monthMap.put("二月", "02");
            monthMap.put("三月", "03");
            monthMap.put("四月", "04");
            monthMap.put("五月", "05");
            monthMap.put("六月", "06");
            monthMap.put("七月", "07");
            monthMap.put("八月", "08");
            monthMap.put("九月", "09");
            monthMap.put("十月", "10");
            monthMap.put("十一月", "11");
            monthMap.put("十二月", "12");

            // 解析格式：十二月 24, 2012
            String[] parts = cleanStr.split("[,\\s]+");
            if (parts.length >= 3) {
                String monthChinese = parts[0];
                String day = parts[1];
                String year = parts[2];

                String monthNum = monthMap.get(monthChinese);
                if (monthNum != null) {
                    // 确保日期是两位数
                    if (day.length() == 1) {
                        day = "0" + day;
                    }
                    String result = year + "年" + monthNum + "月" + day + "日";
                    log.info("中文日期转换：{} -> {}", dateStr, result);
                    return result;
                }
            }

            log.warn("无法解析中文日期格式：{}", dateStr);
            return null;
        } catch (Exception e) {
            log.warn("中文日期解析失败：{}", dateStr, e);
            return null;
        }
    }

    @Override
    public List<TeacherDO> getSimpleTeacherList() {
        return teacherMapper.selectList();
    }

}